package cs294s.liveradar;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Point;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;


public class LocationChooserMap extends MapActivity implements LocationListener{

	private MapView mapView;
	GeoPoint currentPoint;
	MapController mc;
	String addr;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.locationchoosermap);

		//Setting up mapview
		mapView = (MapView)findViewById(R.id.mapview);
		// mapView.setBuiltInZoomControls(true);

		int lat = getIntent().getIntExtra("lat", 0);
		int lon = getIntent().getIntExtra("lon", 0);


		Button chooseLocationButton = (Button) findViewById(R.id.map_chooseLocationButton);
		chooseLocationButton.setOnClickListener(chooseLocationButtonOnClickListener);

		loadMap(lat, lon);
	}


	private Button.OnClickListener chooseLocationButtonOnClickListener
	= new Button.OnClickListener(){
		@Override
		public void onClick(View v) {
			Intent i = new Intent();
			i.putExtra("lat", currentPoint.getLatitudeE6());
			i.putExtra("lon", currentPoint.getLongitudeE6());
			i.putExtra("addr", addr);
			setResult(RESULT_OK, i);
			finish();
		}
	};

	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}

	class MapOverlay extends com.google.android.maps.Overlay
	{
		Geocoder geoCoder = new Geocoder(
				getBaseContext(), Locale.getDefault());

		int initZoomLevel = -1;
		
		public MapOverlay() {
			super();
		}
		@Override
		public boolean draw(Canvas canvas, MapView mapView, 
				boolean shadow, long when) 
		{
			super.draw(canvas, mapView, shadow);                   

			//---translate the GeoPoint to screen pixels---
			Point screenPts = new Point();
			mapView.getProjection().toPixels(currentPoint, screenPts);

			//---add the marker---
			Bitmap bmp = BitmapFactory.decodeResource(
					getResources(), R.drawable.marker);            
			canvas.drawBitmap(bmp, screenPts.x-16, screenPts.y-16, null);         
			return true;
		}

		@Override
		public boolean onTouchEvent(MotionEvent event, MapView mapView) 
		{ 
			//---when user lifts his finger---
			if(event.getAction() == MotionEvent.ACTION_DOWN) {
				initZoomLevel =mapView.getZoomLevel();
			} else if (event.getAction() == MotionEvent.ACTION_MOVE) {
			}else if (event.getAction() == MotionEvent.ACTION_UP) {   
				if(mapView.getZoomLevel() != initZoomLevel) return false;
				currentPoint = mapView.getProjection().fromPixels(
						(int) event.getX(),
						(int) event.getY());

				String add = "";

				try {
					List<Address> addresses = geoCoder.getFromLocation(
							currentPoint.getLatitudeE6()  / 1E6, 
							currentPoint.getLongitudeE6() / 1E6, 1);

					if (addresses.size() > 0) 
					{
						for (int i=0; i<addresses.get(0).getMaxAddressLineIndex(); 
						i++)
							add += addresses.get(0).getAddressLine(i) + "\n";
					}

					Toast.makeText(getBaseContext(), add, Toast.LENGTH_SHORT).show();
				}
				catch (IOException e) {                
					e.printStackTrace();
				} 


				mc.animateTo(currentPoint);

				//---Add a location marker---
				MapOverlay mapOverlay = new MapOverlay();
				List<Overlay> listOfOverlays = mapView.getOverlays();
				listOfOverlays.clear();
				listOfOverlays.add(mapOverlay);   

				mapView.invalidate();
				addr = add.trim();

			}                            
			return false;
		}  
	}


	public void loadMap(int latE6, int lonE6)
	{
		mc = mapView.getController();

		LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
		lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);

		currentPoint = new GeoPoint(latE6, lonE6);

		mc.animateTo(currentPoint);
		mc.setZoom(17); 

		MapOverlay mapOverlay = new MapOverlay();
		List<Overlay> listOfOverlays = mapView.getOverlays();
		listOfOverlays.clear();
		listOfOverlays.add(mapOverlay);  

		mapView.invalidate();
	}

	@Override
	public void onLocationChanged(Location location) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub

	}
}
